package jinyilw.swing.rlaf.ui;

import jinyilw.swing.ComponentTools;
import jinyilw.swing.graphics.RenderingConfig;
import jinyilw.swing.rlaf.theme.RThemeColor;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JScrollBar;
import javax.swing.plaf.ComponentUI;
import javax.swing.plaf.basic.BasicScrollBarUI;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;

/**
 * @author Jinyi
 */
public class RScrollBarUI extends BasicScrollBarUI
{
	public static final int barWidth = 8;
	private static final AlphaComposite alphaComposite = ComponentTools.alphaComposite;
	private static final Dimension d = new Dimension();
	private static final float alpha = 0.75f;
	private static final int arc = 8;
	private static final int minLength = 16;
	private final RenderingConfig renderingConfig = new RenderingConfig();

	public static ComponentUI createUI(JComponent c)
	{
		return new RScrollBarUI();
	}

	@Override
	public void installUI(JComponent c)
	{
		super.installUI(c);
		scrollbar.setOpaque(false);
		scrollBarWidth = barWidth;
	}

	@Override
	protected JButton createDecreaseButton(int orientation)
	{
		return new NullButton();
	}

	@Override
	protected JButton createIncreaseButton(int orientation)
	{
		return new NullButton();
	}

	@Override
	protected void paintTrack(Graphics g, JComponent c, Rectangle r)
	{
	}

	@Override
	protected void paintThumb(Graphics g, JComponent c, Rectangle r)
	{
		if (r.isEmpty() || !scrollbar.isEnabled())
			return;
		Graphics2D g2d = (Graphics2D) g;
		renderingConfig.setAAPainting(g2d);
		Composite saveComposite = g2d.getComposite();
		g2d.setComposite(alphaComposite.derive(alpha));
		Color saveColor = g.getColor(), color = null;
		if (isDragging)
		{
			color = RThemeColor.colorSet.scrollBarColor.brighter();
		} else if (isThumbRollover())
		{
			color = RThemeColor.colorSet.scrollBarColor.brighter();
		} else
		{
			color = RThemeColor.colorSet.scrollBarColor;
		}
		g2d.setColor(color);
		int w = r.width - 1;
		int h = r.height - 1;
		g2d.fillRoundRect(r.x, r.y, w, h, arc, arc);
		g2d.setColor(RThemeColor.themeColor);
		g2d.drawRoundRect(r.x, r.y, w, h, arc, arc);

		renderingConfig.resetAAPainting(g2d);
		g2d.setComposite(saveComposite);
		g2d.setColor(saveColor);
	}

	@Override
	protected void setThumbBounds(int x, int y, int width, int height)
	{
		if (scrollbar.getOrientation() == JScrollBar.VERTICAL)
		{
			if (height < minLength)
				height = minLength;
		} else if (width < minLength)
			width = minLength;
		super.setThumbBounds(x, y, width, height);
		// scrollbar.repaint();
	}

	static class NullButton extends JButton
	{
		private static final long serialVersionUID = -2419027255304069679L;

		@Override
		public Dimension getPreferredSize()
		{
			return d;
		}
	}
}
